import re
from pyassured.core.logger import Log

log = Log()


class GlobalData:
    __set_global_var = {}

    def set_data(self, var, value):

        self.__set_global_var[var] = value
        log.info("添加变量数据到全局配置: 变量名是:{},值是:{}".format(var, value))

    def get_data(self):

        return self.__set_global_var

    def clear(self):
        """清空全局变量"""
        self.__set_global_var.clear()
        log.info("已清空全局变量数据")

    # 解析字符串中全局变量并进行替换
    def resolve_global_var(self, pre_resolve_var, res=None, debugMode=False, global_var_regex=r'\${.*?}'):
        # 优先使用局部变量，如果没有则使用全局变量
        var = {}
        var.update(self.__set_global_var)  # 先添加全局变量
        if res:
            var.update(res)  # 局部变量覆盖全局变量（优先级更高）

        re_global_var = re.compile(global_var_regex)

        def global_var_replace(match_obj):

            start_index = 2
            end_index = -1
            match_value = var.get(match_obj.group()[start_index:end_index])
            return match_value if match_value else match_obj.group()

        resolved_var = re.sub(pattern=re_global_var, string=pre_resolve_var, repl=global_var_replace)

        match = re.search(global_var_regex, pre_resolve_var)

        if debugMode:
            if pre_resolve_var == resolved_var and match is not None:
                log.error("字符串解析前:{},字符串解析后:{}".format(pre_resolve_var, resolved_var))
                log.error("变量未找到:{},请确认是否提取变量".format(pre_resolve_var))
                return ''
            if pre_resolve_var != resolved_var:
                log.info("字符串解析前:{},字符串解析后:{}".format(pre_resolve_var, resolved_var))
        return resolved_var


global_data = GlobalData()
